import os
from typing import Dict, Any
from fastapi import APIRouter, HTTPException, Body
from fastapi.responses import HTMLResponse

from app.modules.log_manager import log_manager

router = APIRouter(prefix="/logs", tags=["日志管理"])


@router.get("/loggers", summary="获取所有Logger列表")
async def get_all_loggers():
    """获取所有已注册的Logger名称"""
    try:
        logger_names = log_manager.get_all_logger_names()
        return {"msg": "ok", "data": sorted(logger_names)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/loggers/{logger_name}", summary="获取Logger详细信息")
async def get_logger_info(logger_name: str):
    """获取特定Logger的详细信息"""
    try:
        info = log_manager.get_logger_info(logger_name)
        return {"msg": "ok", "data": info}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/loggers/{logger_name}/config", summary="更新Logger配置")
async def update_logger_config(logger_name: str, config: Dict[str, Any]):
    """动态更新Logger配置"""
    try:
        level = config.get('level')
        propagate = config.get('propagate')

        success = log_manager.update_logger_config(logger_name, level=level, propagate=propagate)

        if success:
            return {"msg": "ok", "message": f"Logger '{logger_name}' 配置更新成功"}
        else:
            raise HTTPException(status_code=500, detail="配置更新失败")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/loggers/{logger_name}/handlers", summary="为Logger添加处理器")
async def add_handler_to_logger(logger_name: str, handler_config: Dict[str, Any] = Body(...)):
    """为Logger添加处理器"""
    try:
        success = log_manager.add_handler_to_logger(logger_name, handler_config)
        
        if success:
            return {"msg": "ok", "message": f"已为Logger '{logger_name}' 添加处理器"}
        else:
            raise HTTPException(status_code=500, detail="添加处理器失败")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/loggers/{logger_name}/handlers/{handler_index}", summary="从Logger移除处理器")
async def remove_handler_from_logger(logger_name: str, handler_index: int):
    """从Logger移除处理器"""
    try:
        success = log_manager.remove_handler_from_logger(logger_name, handler_index)
        
        if success:
            return {"msg": "ok", "message": f"已从Logger '{logger_name}' 移除处理器 {handler_index}"}
        else:
            raise HTTPException(status_code=500, detail="移除处理器失败")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/loggers/{logger_name}/diagnose", summary="诊断Logger配置")
async def diagnose_logger(logger_name: str):
    """诊断特定Logger的配置"""
    try:
        diagnosis = log_manager.diagnose_logger(logger_name)
        return {"msg": "ok", "data": diagnosis}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/stats", summary="获取日志统计信息")
async def get_log_stats():
    """获取日志统计信息"""
    try:
        stats = log_manager.get_stats()
        return {"msg": "ok", "data": stats}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/stats", summary="重置日志统计信息")
async def reset_log_stats():
    """重置日志统计信息"""
    try:
        log_manager.reset_stats()
        return {"msg": "ok", "message": "统计信息已重置"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/manager", summary="日志管理界面", response_class=HTMLResponse)
async def log_manager_ui():
    """提供日志管理前端界面"""
    static_file_path = os.path.join(os.path.dirname(__file__), "..", "..", "static", "log_manager.html")
    try:
        with open(static_file_path, "r", encoding="utf-8") as f:
            html_content = f.read()
        return HTMLResponse(content=html_content)
    except FileNotFoundError:
        return HTMLResponse(content="<h1>日志管理界面文件未找到</h1>", status_code=404)
